import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/index',
    name: 'inedx',
    component: ()=> import('../views/Index.vue'),
    children:[
        {
            path:'/index/home',
            name:'home',
            meta: { title: '首页' },
            component:()=> import('../views/Index/Home.vue')
        },
        {
            path: '/index/order',
            name: 'order',
            meta: { title: '订单' },
            component: () => import('../views/Index/Order.vue')
        },
        {
            path: '/index/mine',
            name: 'mine',
            meta: { title: '我的' },
            component: () => import('../views/Index/Mine.vue')
        },
        {
            path: '/index/baobao',
            name: 'baobao',
            meta: { title: '爆爆团' },
            component: () => import('../views/Index/Baobao.vue')
        },
        {
            path: '/index',
            redirect: '/index/home'
        },
        //404路由
        {
            path: '*',
            component: () => import('../views/NotFound.vue')
        }
    ]
  },
    {
        path: '/login',
        name: 'about',
        meta: { title: '登陆' },
        component: () => import('../views/Login.vue'),
    },
    {
        path: '/register',
        name: 'register',
        meta: { title: '注册' },
        component: () => import('../views/Register.vue'),

    },
    {
        path: '/',
        redirect: '/index'
    },
    //404路由
    {
        path: '*',
        component: () => import('../views/NotFound.vue')
    }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
    document.title = to.meta.title;
    var token = localStorage.getItem('token');
    if (to.path == '/register') { //跳往 注册页 , 允许跳转
        next();
    } else {
        if (to.path == '/login') { //跳往 登录页
            if (token) { //已登录 , 重定向到 "/"
                next('/');
            } else { //未登录 , 允许跳往 登录页
                next();
            }
            // next();
        } else { //跳往 非登录页
            if (to.path == '/index/mine') { //已登录 , 允许访问
                if(token){
                    next();
                }else{
                    next('/login')
                }
            }
            if (to.path == '/index/order') { //已登录 , 允许访问
                if (token) {
                    next();
                } else {
                    next('/login')
                }
            }
        }
    }
    next();
})

export default router
